package org.budo.filestore.ftp;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.budo.filestore.impl.AbstractFileStore;

import lombok.Getter;
import lombok.Setter;

/**
 * @author lmw
 */
@Getter
@Setter
public abstract class AbstractFtpFileStore extends AbstractFileStore {
    private String host;

    private Integer port;

    private String username;

    private String password;

    private FTPClient ftpClient;

    public String getHost() {
        return host;
    }

    protected FTPClient getFtpClient() {
        if (null == this.ftpClient) {
            synchronized (AbstractFtpFileStore.class) {
                if (null == this.ftpClient) {
                    this.ftpClient = this.initFtpClient();
                }
            }
        }
        return this.ftpClient;
    }

    private FTPClient initFtpClient() {
        try {
            FTPClient ftpClient = new FTPClient();
            if (null == this.getPort()) {
                ftpClient.connect(this.getHost());
            } else {
                ftpClient.connect(this.getHost(), this.getPort());
            }

            Integer connectReply = ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(connectReply)) {
                ftpClient.disconnect();
            } else {
                ftpClient.login(this.getUsername(), this.getPassword());
                ftpClient.pasv();
                ftpClient.enterLocalPassiveMode();
            }

            ftpClient.setFileType(FTP.BINARY_FILE_TYPE); // 以BINARY格式传送文件
            return ftpClient;
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }
    }
}